/**    
 * @{#} BingliDetailActivity.java Create on 2014-6-9 下午8:50:36    
 *          
 * @author <a href="mailto:evan0502@qq.com">Evan</a>   
 * @version 1.0    
 */
package com.smiier.skin;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.HorizontalScrollView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import cn.o.app.json.JsonUtil;
import cn.o.app.net.INetTask;
import cn.o.app.net.NetTaskListener;
import cn.o.app.ui.OImageView;
import cn.o.app.ui.photo.PhotoActivity;
import cn.o.app.ui.photo.PhotoExtra;
import cn.o.app.util.OUtil;
import cn.skinapp.R;

import com.evan.common.adapter.BaseListAdapter;
import com.evan.common.connection.ConnectionCommon;
import com.evan.common.pullrefresh.PullToRefreshBase;
import com.evan.common.pullrefresh.PullToRefreshBase.OnRefreshListener;
import com.evan.common.pullrefresh.PullToRefreshListView;
import com.evan.common.share.ShareWXUtils;
import com.evan.common.widget.pop.ActionItem;
import com.evan.common.widget.pop.TitlePopup;
import com.evan.common.widget.pop.TitlePopup.OnItemOnClickListener;
import com.lidroid.xutils.BitmapUtils;
import com.smiier.skin.constant.Constant;
import com.smiier.skin.extra.QuestionAnswerExtra;
import com.smiier.skin.net.MRQuestionGetListTask;
import com.smiier.skin.net.MRQuestionGetListTask.MRQuestionGetListRequest;
import com.smiier.skin.net.MRQuestionGetListTask.MRQuestionGetListResponse;
import com.smiier.skin.net.entity.QuestionAnswer;
import com.smiier.skin.ui.BasicActivity;
import com.smiier.skin.util.GlobalSettings;
import com.smiier.skin.utils.CommonUtility;
import com.umeng.analytics.MobclickAgent;

public class BingliDetailActivity extends BasicActivity implements
		OnRefreshListener<ListView> {

	public PullToRefreshListView list_question_detail;
	BingliDetailAdapter adapter;

	MRQuestionGetListRequest mRequest = new MRQuestionGetListRequest();
	int start_qid;
	ArrayList<Object> array = new ArrayList<Object>();
	String qid;

	TextView text_job, text_guominshi, text_bingshi, text_patient_name;
	OImageView img_patient_icon;
	LinearLayout ll_add_question, ll_yaowuguomin, ll_bingshi,
			ll_buliang_guominshi;

	JSONObject patient;

	// 添加个人信息头显示
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_question_detail);

		init();
		setNavTitle("病历");
		setNavRightBtn("操作");

		try {
			patient = new JSONObject(getIntent().getStringExtra(
					Constant.IDENTITY_KEY)).getJSONObject("User");
		} catch (Exception e) {
			e.printStackTrace();
		}

		View headView = LayoutInflater.from(this).inflate(
				R.layout.view_question_detail_head, null);

		list_question_detail = (PullToRefreshListView) findViewById(R.id.list_question_detail);
		list_question_detail.setOnRefreshListener(this);

		list_question_detail.setPullLoadEnabled(false);
		list_question_detail.setPullRefreshEnabled(false);
		list_question_detail.setScrollLoadEnabled(true);

		mRequest.uid = GlobalSettings.sUid;
		mRequest.pageSize = 10;
		mRequest.token = GlobalSettings.sToken;
		try {
			mRequest.uid = Long.parseLong(patient.getString("Uid"));
		} catch (Exception e) {

		}
		list_question_detail.getListView().addHeaderView(headView);
		// list_question_detail.doPullRefreshing(true);
		adapter = new BingliDetailAdapter(this, array);
		list_question_detail.setAdapter(adapter);
		text_job = (TextView) headView.findViewById(R.id.text_job);
		text_guominshi = (TextView) headView.findViewById(R.id.text_guominshi);
		text_bingshi = (TextView) headView.findViewById(R.id.text_bingshi);
		ll_yaowuguomin = (LinearLayout) headView
				.findViewById(R.id.ll_yaowuguomin);
		ll_bingshi = (LinearLayout) headView.findViewById(R.id.ll_bingshi);
		ll_buliang_guominshi = (LinearLayout) findViewById(R.id.ll_buliang_guominshi);

		img_patient_icon = (OImageView) headView
				.findViewById(R.id.img_patient_icon);
		text_patient_name = (TextView) headView
				.findViewById(R.id.text_patient_name);

		TextView text_new_question = (TextView) headView
				.findViewById(R.id.text_new_question);
		text_new_question.setText("新增病案");

		ll_add_question = (LinearLayout) findViewById(R.id.ll_add_question);
		ll_add_question.setVisibility(View.VISIBLE);

		list_question_detail.doPullRefreshing(true);

		loadUserInfo();

		IntentFilter filter = new IntentFilter(Constant.RECIVER_COMMENT);
		registerReceiver(receiver, filter);
	}

	public void loadData(boolean isShowDialog) {
		mRequest.startQid = start_qid;
		MRQuestionGetListTask task = new MRQuestionGetListTask();
		task.setRequest(mRequest);
		task.addListener(new NetTaskListener<MRQuestionGetListTask.MRQuestionGetListRequest, MRQuestionGetListTask.MRQuestionGetListResponse>() {

			@Override
			public void onException(
					INetTask<MRQuestionGetListRequest, MRQuestionGetListResponse> task,
					Exception e) {
				list_question_detail.doComplete();
			}

			@Override
			public void onComplete(
					INetTask<MRQuestionGetListRequest, MRQuestionGetListResponse> task,
					MRQuestionGetListResponse response) {
				list_question_detail.doComplete();
				if (response.ResultCode != 200) {
					toast(R.string.server_unavailable);
					list_question_detail.setContextEmptyType(true, 2);
					return;
				}
				try {
					JSONArray arr = new JSONArray(JsonUtil
							.convert(response.Res.Questions));
					if (arr.length() > 0) {
						CommonUtility.putAll(array, arr, true);
						list_question_detail.setHasMoreData(true);
					} else {
						list_question_detail.setHasMoreData(false);
					}
					if (array.size() > 0) {
						start_qid = ((JSONObject) array.get(array.size() - 1))
								.getInt("Qid");
					}
					adapter.notifyUpdate();
					if (array.size() < 1) {
						list_question_detail.setContextEmptyType(true, 2);
					} else {
						list_question_detail.setContextEmptyType(false, 2);
					}
				} catch (Exception e) {

				}
			}
		});
		add(task);
	}

	void loadUserInfo() {
		try {
			text_job.setText(patient.getString("Job"));
			StringBuilder sb = new StringBuilder();
			sb.append(CommonUtility.sex.get(patient.getInt("Sex")))
					.append("，")
					.append(CommonUtility.getAgeByBirthday(patient
							.getString("Birth"))).append("岁")
			// .append("，")
			// .append(patient.getString("Nation"))
			// .append("，")
			// .append("现居")
			// .append(patient.getString("City"))
			// .append("，")
			// .append(CommonUtility.marry.get(patient
			// .getInt("Marital_Status")))
			;
			String guominshi = CommonUtility.convertJSONArray2String(
					patient.getJSONArray("DrugAllergen"), ",");
			if (CommonUtility.isNull(guominshi)) {
				ll_yaowuguomin.setVisibility(View.GONE);
			} else {
				text_guominshi.setText(guominshi);
			}

			String bingshi = CommonUtility.convertJSONArray2String(
					patient.getJSONArray("MedicalHistory"), ",");

			if (CommonUtility.isNull(bingshi)) {
				ll_bingshi.setVisibility(View.GONE);
			} else {
				text_bingshi.setText(bingshi);
			}

			if (ll_yaowuguomin.getVisibility() == View.VISIBLE
					|| ll_bingshi.getVisibility() == View.VISIBLE) {
				ll_buliang_guominshi.setVisibility(View.VISIBLE);
			} else {
				ll_buliang_guominshi.setVisibility(View.GONE);
			}
			if (CommonUtility.isDoctor()
					|| patient.getInt("Uid") == GlobalSettings.sUid) {
				img_patient_icon.setVisibility(View.VISIBLE);
				// mBitmapUtils.display(img_patient_icon,
				// GlobalSettings.SERVER_IMG_URL
				// + GlobalSettings.sUser.Pic + Constant.IMG_TH,
				// new OBitmapLoadCallBack<View>());
				CommonUtility.displayHeadImage(img_patient_icon, mBitmapUtils,
						GlobalSettings.SERVER_IMG_URL
								+ GlobalSettings.sUser.Pic + Constant.IMG_TH,
						getContext().getResources(), GlobalSettings.sUser.Sex);
				text_patient_name.setText(patient.getString("Name"));
				text_patient_name.setVisibility(View.VISIBLE);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.evan.common.pullrefresh.PullToRefreshBase.OnRefreshListener#
	 * onPullDownToRefresh(com.evan.common.pullrefresh.PullToRefreshBase)
	 */
	@Override
	public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
		start_qid = 0;
		array.clear();
		loadData(false);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.evan.common.pullrefresh.PullToRefreshBase.OnRefreshListener#
	 * onPullUpToRefresh(com.evan.common.pullrefresh.PullToRefreshBase)
	 */
	@Override
	public void onPullUpToLoadMore(PullToRefreshBase<ListView> refreshView) {
		loadData(false);
	}

	TitlePopup titlePopup;

	public void onClick(View view) {
		int id = view.getId();
		if (id == R.id.btn_left) {
			finish();
		} else if (id == R.id.text_right) {
			if (CommonUtility.isNull(titlePopup)) {
				titlePopup = new TitlePopup(this, CommonUtility.dip2px(this,
						140), android.view.ViewGroup.LayoutParams.WRAP_CONTENT);

				titlePopup.addAction(new ActionItem(this, "编辑病例"));
				titlePopup.addAction(new ActionItem(this, "分享至微信好友"));
				titlePopup.addAction(new ActionItem(this, "创建患者账号"));

				titlePopup.setItemOnClickListener(new OnItemOnClickListener() {

					@Override
					public void onItemClick(ActionItem item, int position) {
						switch (position) {
						case 0:
							Intent intent = new Intent(getContext(),
									CreateBingliActivity.class);
							intent.putExtra(Constant.IDENTITY_KEY,
									patient.toString());
							startActivity(intent);
							break;

						case 1:
							try {
								String url = "http://www.pifupro.com/mf/Share_MR_QuestionList.aspx?Platform=android&mr_uid="
										+ patient.getString("Uid");
								ShareWXUtils.getInstance(getContext())
										.share2WXWEB(url,
												patient.getString("Name"), "",
												false);
							} catch (Exception e) {
								e.printStackTrace();
							}
							break;
						case 2:
							intent = new Intent(getContext(),
									InvitePatientFromBingliActivity.class);
							try {
								intent.putExtra(Constant.IDENTITY_KEY,
										patient.getString("Uid"));
							} catch (Exception e) {
								e.printStackTrace();
							}
							startActivity(intent);
							break;
						}
					}
				});
			}
			titlePopup.show(view);
		} else if (id == R.id.ll_add_question) {
			Intent intent = new Intent(getContext(),
					CreateQuestionActivity.class);
			intent.putExtra(Constant.IDENTITY_KEY_BINGLI, true);
			try {
				intent.putExtra(Constant.IDENTITY_KEY, patient.getString("Uid"));
			} catch (Exception e) {
				e.printStackTrace();
			}
			startActivityForResult(intent, 0);
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onActivityResult(int, int,
	 * android.content.Intent)
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (resultCode) {
		case Constant.ACTIVITY_CREATE_BINGLI_SUCCESSFULLY:
			list_question_detail.doPullRefreshing(true);
			break;
		}
	}

	BroadcastReceiver receiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			try {
				QuestionAnswerExtra extra = new QuestionAnswerExtra();
				extra.getFrom(intent);
				QuestionAnswer answer = extra.getQuestionAnswer();
				JSONObject newData = JsonUtil.convertToObject(answer);
				JSONObject o = null;
				int size = array.size();
				for (int i = 0; i < size; i++) {
					o = (JSONObject) array.get(i);
					if (o.getInt("Qid") == answer.Qid) {
						array.remove(i);
						array.add(i, newData);
						adapter.notifyUpdate();
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	};

	@Override
	protected void onDestroy() {
		super.onDestroy();
		CommonUtility.unRegisteReciver(this, receiver);
	}

	@SuppressLint("InflateParams")
	public static class BingliDetailAdapter extends BaseListAdapter {

		protected BitmapUtils mBitmapUtils;

		public BingliDetailAdapter(Activity activity, ArrayList<Object> array) {
			super(activity, array);
			this.activity = activity;
			mBitmapUtils = new BitmapUtils(activity);
		}

		class ViewHolder {
			TextView text_content, text_buwei_zhengzhuang, text_jieda_result,
					text_bingzhengtuiduan, text_zhiliaocuoshi;
			LinearLayout ll_imgs, ll_result;
			RelativeLayout ll_status;
			Button btn_edit_bingan, btn_edit_zhenduan;
			HorizontalScrollView hsv_imgs;
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.widget.Adapter#getView(int, android.view.View,
		 * android.view.ViewGroup)
		 */
		@Override
		public View getView(int position, View convertView, ViewGroup root) {
			ViewHolder viewHolder = null;
			if (CommonUtility.isNull(convertView)) {
				convertView = inflater.inflate(R.layout.item_bingli_detail,
						null);
				viewHolder = new ViewHolder();
				viewHolder.text_content = (TextView) convertView
						.findViewById(R.id.text_content);
				viewHolder.text_buwei_zhengzhuang = (TextView) convertView
						.findViewById(R.id.text_buwei_zhengzhuang);
				viewHolder.ll_imgs = (LinearLayout) convertView
						.findViewById(R.id.ll_imgs);
				viewHolder.ll_result = (LinearLayout) convertView
						.findViewById(R.id.ll_result);
				viewHolder.ll_status = (RelativeLayout) convertView
						.findViewById(R.id.ll_status);

				viewHolder.text_jieda_result = (TextView) convertView
						.findViewById(R.id.text_jieda_result);
				viewHolder.text_bingzhengtuiduan = (TextView) convertView
						.findViewById(R.id.text_bingzhengtuiduan);
				viewHolder.text_zhiliaocuoshi = (TextView) convertView
						.findViewById(R.id.text_zhiliaocuoshi);
				viewHolder.btn_edit_bingan = (Button) convertView
						.findViewById(R.id.btn_edit_bingan);
				viewHolder.btn_edit_zhenduan = (Button) convertView
						.findViewById(R.id.btn_edit_zhenduan);
				viewHolder.hsv_imgs = (HorizontalScrollView) convertView
						.findViewById(R.id.hsv_imgs);

				viewHolder.btn_edit_bingan.setOnClickListener(listener);
				viewHolder.btn_edit_zhenduan.setOnClickListener(listener);
				CommonUtility.setViewHolderTag(convertView, viewHolder);
			} else {
				viewHolder = (ViewHolder) CommonUtility
						.getViewHolderTag(convertView);
			}
			try {
				JSONObject object = (JSONObject) getItem(position);
				JSONObject question = object.getJSONObject("Question");
				JSONObject answer = object.getJSONObject("Answer");

				viewHolder.text_content.setText(question.getString("Content"));
				viewHolder.btn_edit_bingan.setTag(question);
				viewHolder.btn_edit_zhenduan.setTag(object);

				StringBuilder sbBuweiZhengzhuang = new StringBuilder();

				sbBuweiZhengzhuang.append(CommonUtility
						.convertJSONArray2String(question.getJSONArray("Part"),
								","));
				String symptom = CommonUtility.convertJSONArray2String(
						question.getJSONArray("Symptom"), ",");
				if (!CommonUtility.isNull(sbBuweiZhengzhuang.toString().trim())
						&& !CommonUtility.isNull(symptom.trim())) {
					sbBuweiZhengzhuang.append(" | ");
				}
				sbBuweiZhengzhuang.append(symptom);

				viewHolder.text_buwei_zhengzhuang.setText(sbBuweiZhengzhuang
						.toString());

				String jieda_result = answer.getString("Malady");
				if (!CommonUtility.isNull(jieda_result)) {
					viewHolder.ll_result.setVisibility(View.VISIBLE);
					viewHolder.ll_status.setVisibility(View.VISIBLE);
					viewHolder.text_jieda_result.setText(jieda_result);
					viewHolder.text_bingzhengtuiduan.setText(answer
							.getString("Disease_Inference"));
					viewHolder.btn_edit_zhenduan.setText("编辑诊断");

					JSONArray treatments = answer.getJSONArray("Treatments");
					StringBuilder sb = new StringBuilder();
					for (int i = 0; i < treatments.length(); i++) {
						JSONObject o = treatments.getJSONObject(i);
						String drug = o.getString("Drug");
						String advice = o.getString("Advice");
						sb.append(o.getString("Drug"));
						if (!CommonUtility.isNull(drug)
								&& !CommonUtility.isNull(advice)) {
							sb.append(" | ");
						}
						sb.append(advice);
						if (i < treatments.length() - 1) {
							sb.append("\n");
						}
					}
					viewHolder.text_zhiliaocuoshi.setText(sb);
				} else {
					viewHolder.ll_result.setVisibility(View.GONE);
					viewHolder.ll_status.setVisibility(View.GONE);
					viewHolder.btn_edit_zhenduan.setText("创建诊断");
				}

				viewHolder.text_content.setText(question.getString("Content"));

				if (CommonUtility.isDoctor() && CommonUtility.isCert()) {
					JSONArray pics = question.getJSONArray("Pic");
					viewHolder.ll_imgs.removeAllViews();
					if (pics.length() > 0) {
						viewHolder.hsv_imgs.setVisibility(View.VISIBLE);
						String[] picStrs = new String[pics.length()];
						for (int i = 0; i < pics.length(); i++) {
							OImageView layout = new OImageView(activity);
							layout.setIsRoundRect(true);
							layout.setId(R.id.imgLayout_show);
							layout.setScaleType(ScaleType.CENTER_CROP);
							LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
									(int) OUtil.dp2px(activity, 70),
									(int) OUtil.dp2px(activity, 70));
							layoutParams.setMargins(0, 0,
									(int) OUtil.dp2px(activity, 8), 0);
							layout.setLayoutParams(layoutParams);

							final String path = pics.getString(i)
									+ Constant.IMG_TH;
							mBitmapUtils.display(layout,
									GlobalSettings.SERVER_IMG_URL + path);
							// CommonUtility.displayHeadImage(layout,
							// mBitmapUtils, GlobalSettings.SERVER_IMG_URL
							// + path, convertView.getResources(),
							// GlobalSettings.sUser.Sex);
							viewHolder.ll_imgs.addView(layout);
							// layout.setImageFileTag(pics.getString(i)
							// + Constant.IMG_SRC);
							layout.setOnClickListener(listener_img);
							layout.setTag(i);
							layout.setTag(R.id.tag_obj, picStrs);
							picStrs[i] = ConnectionCommon.getInstance().REQUEST_PIC_PATH
									+ pics.getString(i) + Constant.IMG_SRC;

						}
					} else {
						viewHolder.hsv_imgs.setVisibility(View.GONE);
					}
				} else {
					viewHolder.hsv_imgs.setVisibility(View.GONE);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			return convertView;
		}

		OnClickListener listener_img = new OnClickListener() {

			@Override
			public void onClick(View view) {
				int position = (Integer) view.getTag();
				String[] pics = (String[]) view.getTag(R.id.tag_obj);
				PhotoExtra extra = new PhotoExtra();
				extra.setDisplayedIndex(position);
				extra.setPhotos(OUtil.asArrayList(pics));
				Intent intent = new Intent(activity, PhotoActivity.class);
				extra.putTo(intent);
				activity.startActivity(intent);
			}
		};

		HashMap<String, Object> params;
		HashMap<String, Object> jieda_params;
		OnClickListener listener = new OnClickListener() {

			@Override
			public void onClick(final View view) {
				int id = view.getId();
				if (id == R.id.btn_edit_bingan) {
					Intent intent = new Intent(activity,
							CreateQuestionActivity.class);
					intent.putExtra(Constant.IDENTITY_KEY_BINGLI, true);
					intent.putExtra(Constant.IDENTITY_KEY_BINGLI_EDIT, true);
					intent.putExtra(Constant.IDENTITY_KEY, view.getTag()
							.toString());
					activity.startActivityForResult(intent, 0);
				} else if (id == R.id.btn_edit_zhenduan) {
					Intent intent = new Intent(activity,
							ZhiliaofanganActivity.class);
					intent.putExtra(Constant.IDENTITY_KEY_BINGLI, true);
					intent.putExtra(Constant.IDENTITY_KEY, view.getTag()
							.toString());
					activity.startActivityForResult(intent, 0);
				}
			}
		};

	}
	
/*	@Override
	public void onResume() {
		super.onResume();
		MobclickAgent.onResume(getContext());
	}

	@Override
	public void onPause() {
		super.onPause();
		MobclickAgent.onPause(getContext());
	}*/
}
